package com.ostms.adv.utils;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HttpTools {
    private static final String TAG = HttpTools.class.getSimpleName();
    private Context context;
    private LOG log;

    public HttpTools(Context context) {
        this.context = context;
    }

    public void sendPostdata(final String url, FormBody.Builder builder, final HttpLisenner lisenner) {
//        log.i(TAG, "请求地址：" + url);
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS).build();
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Content-Type", "application/json;charset=utf-8")
                .post(builder.build())
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                lisenner.onFailure(call, e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (null != response.body()) {
                    String result = response.body().string();
                    log.i(TAG, "请求地址：" + url);
                    log.i(TAG, "请求结果：" + result);
                    lisenner.onResponse(call, result);
                } else {
                    log.i(TAG, "请求结果为空");
                }
            }
        });
    }

    /**
     * 上传文件
     *
     * @param actionUrl 接口地址
     * @param builder   参数
     * @param lisenner  回调
     */
    public void upLoadFile(String actionUrl, MultipartBody.Builder builder, final HttpLisenner lisenner) {
        try {
            //创建Request
            Request request = new Request.Builder()
                    .url(actionUrl)
                    .addHeader("Accept", "application/json")
                    .post(builder.build())
                    .build();
            new OkHttpClient().newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e(TAG, e.toString());
                    lisenner.onFailure(call, e);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        String result = response.body().string();
                        lisenner.onResponse(call, result);
                    } else {
                        lisenner.onFailure(call, null);
                    }
                }
            });
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
    }

    /**
     * 下载APK
     *
     * @param url      下载流地址
     * @param downUrl  APP的地址
     * @param saveDir  保存文件夹名
     * @param builder  入参
     * @param listener 回调监听
     */
    public void downloadAPK(final String url, final String downUrl, final String saveDir, FormBody.Builder builder, final OnDownloadListener listener) {
        Request request = new Request.Builder()
                .post(builder.build()).url(url).build();
        new OkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 下载失败
                listener.onDownloadFailed();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (200 == response.code()) {
                    InputStream is = null;
                    byte[] buf = new byte[2048];
                    int len = 0;
                    FileOutputStream fos = null;
                    // 储存下载文件的目录
                    String savePath = isExistDir(saveDir);
                    try {
                        is = response.body().byteStream();
                        long total = response.body().contentLength();
                        String fileName = downUrl.substring(downUrl.lastIndexOf("/") + 1);
                        File file = new File(savePath, fileName);
                        fos = new FileOutputStream(file);
                        long sum = 0;
                        while ((len = is.read(buf)) != -1) {
                            fos.write(buf, 0, len);
                            sum += len;
                            int progress = (int) (sum * 1.0f / total * 100);
                            // 下载中
                            listener.onDownloading(progress);
                        }
                        fos.flush();
                        // 下载完成
                        listener.onDownloadSuccess();
                    } catch (Exception e) {
                        listener.onDownloadFailed();
                    } finally {
                        try {
                            if (is != null)
                                is.close();
                        } catch (IOException e) {
                        }
                        try {
                            if (fos != null)
                                fos.close();
                        } catch (IOException e) {
                        }
                    }
                } else {
                    listener.onDownloadFailed();
                }
            }
        });
    }

    public interface OnDownloadListener {
        /**
         * 下载成功
         */
        void onDownloadSuccess();

        /**
         * @param progress 下载进度
         */
        void onDownloading(int progress);

        /**
         * 下载失败
         */
        void onDownloadFailed();

    }

    /**
     * @param saveDir
     * @return
     * @throws IOException 判断下载目录是否存在
     */
    private String isExistDir(String saveDir) {
        // 下载位置
        File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir);
        if (!downloadFile.exists()) {
            downloadFile.mkdirs();
        }
        String savePath = downloadFile.getAbsolutePath();
        return savePath;
    }

    /**
     * @param url
     * @return 从下载连接中解析出文件名
     */
    private String getNameFromUrl(String url, String advCode) {
        if (null == advCode) {
            return url.substring(url.lastIndexOf("/") + 1, url.length());
        }
        return advCode + url.substring(url.lastIndexOf("."));
    }

    public interface HttpLisenner {
        void onFailure(Call call, IOException e);

        void onResponse(Call call, String result);
    }

    public void downloadAdv(final String url, final String saveDir, final String advCode, final OnDownloadListener1 listener) {
        Request request = new Request.Builder().url(url).build();
        new OkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 下载失败
                listener.onDownloadFailed(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                // 储存下载文件的目录
                String savePath = isExistDir(saveDir);
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    String fileName = getNameFromUrl(url, advCode);
                    File file = new File(savePath, fileName);
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                    }
                    fos.flush();
                    // 下载完成
                    listener.onDownloadSuccess();
                } catch (Exception e) {
                    listener.onDownloadFailed(e);
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                }
            }
        });
    }

    public interface OnDownloadListener1 {
        /**
         * 下载成功
         */
        void onDownloadSuccess();

        /**
         * 下载失败
         */
        void onDownloadFailed(Throwable e);
    }
}
